package com.team.ai.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.team.ai.controller.form.*;
import com.team.ai.controller.vo.UserLoginVO;
import com.team.ai.controller.vo.UserRegisterVO;
import com.team.ai.controller.vo.UserVO;
import com.team.ai.entity.ResultEntity;
import com.team.ai.entity.User;
import com.team.ai.exception.BusinessException;
import com.team.ai.exception.BusinessExceptionEnum;
import com.team.ai.service.UserService;
import com.team.ai.service.util.MD5Util;
import com.team.ai.service.util.Result;
import com.team.ai.tool.KoDoTool;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.*;

@CrossOrigin//跨域
@RestController//遵循RestFul
@RequestMapping("v2/User/")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);//日志getLogger需要传入的类名
    @Resource
    private RedisTemplate<String, String> redisTemplate;//Redis工具类
    @Resource
    UserService userService;

    @Resource
    KoDoTool koDoTool;


    @Value("${project.localfilepath}")
    private String localFilePath;//本地文件存储地址

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody LoginForm form) {
        User user = userService.login(form.getName(), form.getPassword());
//        String password = user.getPassword();
        if (Objects.isNull(user)){
            return Result.error("用户名或密码错误！");
        }
        int userId = user.getId();
        //客户端注册用户登录
        StpUtil.login(userId);
        String token = StpUtil.getTokenValue();
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);
        return Result.ok(userLoginVO);
    }

    /**
     * 用户登录,根据手机号+验证码  By Phone SmsCode
     */
    @PostMapping("/loginByPhone")
    public Result<UserLoginVO> login(@RequestBody @Valid LoginByPhoneForm form) {
        String phone = form.getPhone();
        User user = userService.selectByPhone(phone);// login(form.getName(), form.getPassword());
        //手机号没注册（对应用户不存在）
        if (ObjectUtil.isNull(user)) {
            throw new BusinessException(BusinessExceptionEnum.USER_PHONE_EXIST);
        }
        //验证码是否还有效
        String code = redisTemplate.opsForValue().get(phone);
        if (!StrUtil.equals(code, form.getCode())) {
            throw new BusinessException(BusinessExceptionEnum.USER_SMSCODE_INVALID);
        }
        Integer userId = user.getId();
        //客户端注册用户登录
        StpUtil.login(userId, "Mobile");
        String token = StpUtil.getTokenValue();

        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);
        return Result.ok(userLoginVO);
    }

    /**
     * 用户注册 无需token
     */
    @PostMapping("register")
    public String register(
            @RequestParam(value = "name", defaultValue = "-1") String name,
            @RequestParam(value = "password", defaultValue = "-1") String password,
            @RequestParam(value = "gender", defaultValue = "-1") int gender,
            @RequestParam(value = "email", defaultValue = "-1") String email,
            @RequestParam(value = "phone", defaultValue = "-1") String phone,
            @RequestParam(value = "nickName", defaultValue = "-1") String nickName

    ) {
        String avatar = "http://s4oh1k5hp.bkt.clouddn.com/1.jpg";
        return userService.insert(name, password, gender, email, phone, nickName, avatar);
    }

    /**
     * 修改用户信息
     */

    @SaCheckLogin
    @PostMapping("update")
    public Result update(
            @RequestBody @Valid UserUpdateForm form
    ) {
        int userId = StpUtil.getLoginIdAsInt();
        //如果不是登录用户数据，则抛出异常
        if (userId != form.getId()) {
            throw new BusinessException(BusinessExceptionEnum.REQUEST_FORBIDEN_DATA_NOT_YOUR);
        }
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
        }
        //这里时不能更改密码的
        form.setPassword(null);
        User userForUpdate = new User();
        BeanUtils.copyProperties(form, userForUpdate);

        if (userService.update(
                userForUpdate.getName(), userForUpdate.getPhone(), userForUpdate.getEmail()
                , userForUpdate.getGender(), userForUpdate.getNickName(),
                 userForUpdate.getRemark(), userForUpdate.getId()
        ) > 0) {//返回成功
            return Result.ok();
        } else { //返回失败
            return Result.error();
        }
    }

    /**
     * 修改用户密码
     */
    @SaCheckLogin
    @PostMapping("updatepwd")
    public Result upadatepwd(@RequestBody @Valid UserUpdatePwdForm form
    ) {
        int userId = StpUtil.getLoginIdAsInt();
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
        }
        //若密码不为空字符，则表明用户打算更改密码
        String passwordOld = form.getPasswordOld();
        String passwordOldMd5 = MD5Util.md5Encode(passwordOld + user.getSalt(), "UTF-8");
//    if (!StrUtil.equals(passwordOld, passwordOldMd5)) {
//        throw new BusinessException(BusinessExceptionEnum.USER_OLD_PASSWORD_ERROR);
//    }
//
        String password = user.getPassword();
        if (!StrUtil.equals(passwordOld, password)) {
            throw new BusinessException(BusinessExceptionEnum.USER_OLD_PASSWORD_ERROR);
        }

        String passwordNew = form.getPasswordNew();
        //String passwordMd5 = MD5Util.md5Encode(passwordNew + user.getSalt(), "UTF-8");
//    User userForUpdate = new User();
//    userForUpdate.setId(userId);
//    userForUpdate.setPassword(passwordMd5);

        if (userService.updatepwd(userId, passwordNew)) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }

    @Transactional
    @PostMapping("upFile")
    public String upFile(
            @RequestParam Map<String, String> map
    ) {
        Integer id = Integer.valueOf(map.get("id"));
        String path = map.get("path");
        return ResultEntity.success(userService.addAvatar(id, path));//返回七牛云的文件路径字符串
    }


    /**
     * 获取图片绝对路径
     */
    @Transactional
    @PostMapping("getAvatarPath")
    public String getAvatarPath(
            @RequestParam("file") MultipartFile file
    ) {
        String SuffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//获取文件后缀名
        String FileNewName = UUID.randomUUID() + SuffixName;//新的文件名
        File dest = new File(localFilePath + FileNewName);//生成新的文件
        if (!dest.getParentFile().exists()) {//判定文件夹是否存在
            dest.getParentFile().mkdir();//生成文件夹
        }
        try {
            file.transferTo(dest);//将临时文件转为正式文件
            String koDoString = koDoTool.UploadFile(localFilePath + FileNewName);//上传到七牛云
            //userService.addAvatar(id,koDoString);
            System.out.println(koDoString);

            return ResultEntity.success(koDoString);//返回七牛云的文件路径字符串
        } catch (Exception e) {
            logger.error(e.getMessage());//输出日志
            return ResultEntity.fail(-10001);//返回错误代码
        }
    }

    /**
     * 获取图片数组绝对路径
     * @param file
     * @return
     */

    @Transactional
    @PostMapping("getPath")
    public String getPath(
            @RequestParam("file") List<MultipartFile> file
    ) {
        List<String> urlList = new ArrayList<>();
        for (int j=0;j<file.size();j++){
            String SuffixName = file.get(j).getOriginalFilename().substring(file.get(j).getOriginalFilename().lastIndexOf("."));//获取文件后缀名
            String FileNewName = UUID.randomUUID() + SuffixName;//新的文件名
            File dest = new File(localFilePath + FileNewName);//生成新的文件
            if (!dest.getParentFile().exists()) {//判定文件夹是否存在
                dest.getParentFile().mkdir();//生成文件夹
            }
            try {
                file.get(j).transferTo(dest);//将临时文件转为正式文件
                String koDoString = koDoTool.UploadFile(localFilePath + FileNewName);//上传到七牛云
                urlList.add(koDoString);
                //userService.addAvatar(id,koDoString);
                //return communityService.insert(userId,content,urlList.toString());//返回七牛云的文件路径字符串
                //return urlList.toString();
            } catch (Exception e) {
                return ResultEntity.fail(-10001);//返回错误代码
            }
        }
        return ResultEntity.success(urlList);
    }

    /**
     * 根据id查询用户信息
     */
    @GetMapping("getUserDetail")
    public Result<UserVO> getUserDetail() {
        Integer userId = StpUtil.getLoginIdAsInt();
        User user = userService.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BusinessException(BusinessExceptionEnum.DATA_NOT_EXIST);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.ok(userVO);
    }


    /**
     * 登出
     *
     * @return
     */
    @SaCheckLogin
    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok(); //登出成功
    }

}
